package storage;

import modeller.databasedesignmodel.DatabaseDesign;
import exceptions.UnableToLoadDatabaseDesignException;

import java.io.*;

/**
 * Created by:  Jason Ye
 * Date:        22/05/2012
 * Time:        15:47
 */
public class DesignLoad {

    private DatabaseDesign design;
    private FileInputStream inputStream;

    public DesignLoad(FileInputStream inputStream) {

        try {
            this.design = loadDatabaseDesign(inputStream);
            this.inputStream = inputStream;
        } catch (UnableToLoadDatabaseDesignException e) {
            e.printStackTrace();
        }
    }

    private DatabaseDesign loadDatabaseDesign(FileInputStream in) throws UnableToLoadDatabaseDesignException {

        DatabaseDesign the_design;

        try {

            //open the input stream
            ObjectInputStream save = new ObjectInputStream(in);
            // extract database design from object stream
            the_design = (DatabaseDesign) save.readObject();
            //close object stream
            save.close();

            return the_design;

        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        throw new UnableToLoadDatabaseDesignException();
    }

    public DatabaseDesign getDesign() throws NullPointerException {

        if (design != null) {
            return design;
        } else {
            throw new NullPointerException("Error loading DatabaseDesign from file");
        }
    }

}
